<?php
/**
 *common model 文件
 *@author Cuil <lntschampion@163.com>
 */
class MY_Model extends CI_Model {
    protected $pk = array("id");
	public $db;
    public $type;
     
	function MY_Model(){
		
		parent::__construct();
		$this->conn();
	}
	
	//初始化
	function conn($params = array()){
	 	
		$type = '' ;
		$type =(isset($params['dbname']) && $params['dbname'] )? $params['dbname'] : 'default' ;
		
		$this->db = $this->load->database($type,true);
	}
	
	//插入一条数据
	function insert_one($table,$data){
		
		$this->db->insert($table,$data) ;
		
		return array(
			'affect_num'=>$this->db->affected_rows() ,
			'insert_id'=>$this->db->insert_id(),
			'sql'=>$this->db->last_query()
		);
	}
	
	//查询1条数据，返回结果
	function query_one($sql){		
		return $this->db->query($sql)->row_array();
	}
	
	//查询list data
	function querylist($sql){
		
		$result =array();
		$query = $this->db->query($sql);
		if($query){
			foreach($query->result_array() as $row){
	    		$result[] = $row ;
	    	}		
		}
    	return $result ;
	}
	
	//执行sql语句
	function exec($sql){
		$result = $this->db->query($sql);
		return $result;
	}
	
	//查询返回的结果
	function query_count($sql){
		
		$query = $this->db->query($sql);
		$num_array = $query->result_array();
		$num = 0 ;
		if(isset($num_array[0]) && !empty($num_array[0])){
			foreach ($num_array[0] as $k=>$v){
				$num = $v ;
				break ;
			}
		}	
		return $num ;
	}
	
	//删除数据
	function del_data($sql){
		$query = $this->db->query($sql);
		return $this->db->affected_rows(); //返回影响的行数
	
	}
	
	//修改数据
	function update_data($sql){
		$query = $this->db->query($sql);
		return $this->db->affected_rows(); //返回影响的行数
	}
	
	//判断数据表是否存在
	function isexits($tablename){
		$sql = "SHOW TABLES LIKE '". $tablename."'";
		return $this->db->query($sql)->num_rows();
	}
		
	/**
	 * Active Record
	 * 
	 * 参考手册：
	 * http://codeigniter.org.cn/user_guide/database/active_record.html
	 * 
	 * 例子
	 * $this->MY_Model->query('bjnz_new_admin_user',array('group_id'=>4),array('user_id','user_name'));
	 * 
	 * $where 查询条件
	 * $where['uname'] = $uname;
	 * $where['create_time >= '] = $begin;
	 * 
	 * $orderby 排序
	 * $this->db->order_by('title desc'); 
	 * $this->db->order_by('title desc, name asc'); 
	 * 
	 */
	
	//查询
	function query($table,$where=array(),$cols='*',$limit=0,$offset=0,$orderby='',$in_field='',$in_where=array()){
		
		if(empty($table)){
			exit('请注意参数格式');
		}
		
		$query = array();
		
		//查询列
		$this->db->select($cols);
		
		//排序列
		if(!empty($orderby)){
			$this->db->order_by($orderby);
		}
		if(!empty($in_field)){
			$this->db->where_in("{$in_field}", $in_where);
		}
		
		if(empty($where)){
			if($limit==0){
				$query = $this->db->get($table);
			}else{
				$query = $this->db->get($table, $limit, $offset);
			}
		}else{
			if($limit==0){
				$query = $this->db->get_where($table, $where);
			}else{
				$query = $this->db->get_where($table, $where, $limit, $offset);
			}
		}
		
// 		echo $this->db->last_query(); //查看执行sql
// 		die();
		
		$result =array();
		if($query){
			foreach($query->result_array() as $row){
				$result[] = $row ;
			}
		}
		unset($query);
		return $result ;
	}
	
	//查询数量
	function queryCount($table,$where=array(),$in_field='',$in_where=array()){
		
		if(empty($table)){
			exit('请注意参数格式');
		}
		
		if(!empty($in_field)){
			$this->db->where_in("{$in_field}", $in_where);
		}
		$this->db->where($where);
		$this->db->from($table);
		return $this->db->count_all_results();
	}
	
	//插入一条数据
	function insert($table,$data){
		
		if(empty($table) || empty($data)){
			exit('请注意参数格式');
		}
		
		$this->db->insert($table,$data) ;
		return array(
			'affect_num'=>$this->db->affected_rows() ,
			'insert_id'=>$this->db->insert_id()
		);
	}
	
	//删除数据
	function delete($table,$where){
		
		if(empty($table) || empty($where)){
			exit('请注意参数格式');
		}
		
		$result = $this->db->delete($table, $where);
		return $this->db->affected_rows(); //返回影响的行数
	}
	
	//修改数据
	function update($talbe,$data,$where){
		if(empty($talbe) || empty($data) || empty($where)){
			exit('请注意参数格式');
		}
		$this->db->update($talbe, $data, $where);
		//echo $this->db->last_query(); //查看执行sql
		return $this->db->affected_rows();	//返回影响的行数
	}

	//更新时间为unix时间戳
	function update_time($table,$where,$filed='update_time'){
		$sql = "UPDATE {$table} SET {$filed} = UNIX_TIMESTAMP() WHERE ".$where;
		return $this->exec($sql);
    }

        /**
         * 根据对象ID获取指定对象
         * @param int $id 对象ID
         * @return object 
         */
        function get($id)
        {
            $params = array_combine( $this->pk, array($id) );
            return $this->db->get_where( $this->table, $params, 1 )->row();
        }

        /**
        * 根据唯一字段获取指定对象
        * @param string $key 字段名
        * @param string $value 字段值
        * @return object 
        */
        function getByUK( $key, $value )
        {
            return $this->db->get_where( $this->table, array($key => $value), 1 )->row();
        }
        /**
        * 保存指定对象，若id为null则为创建。
        * 支持复合主键对象，除第一个参数外，所有参数按pk的顺序填入
        * @param array $data
        * @param int $id 要保存对象的ID
        * @return boolean 成功返回true(Insert返回ID)，否则返回false
        */

       public function save( $data, $id = null ){
        if( $id ){
            $args   = func_get_args();
            array_shift( $args );
            $paramsk = array_combine( $this->pk, $args );
            $ret    = $this->db->update( $this->table, $data, $paramsk );
        }else{
            $ret = $this->db->insert( $this->table, $data );
            if ( $ret )
                $ret = $this->db->insert_id();

            if ( $ret === 0 )
                $ret = true;
        }

        
        return $ret;


       }
}
